package com.jysz.certificate.web.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.StrutsStatics;

import com.jysz.certificate.action.AbstractBaseAction;
import com.jysz.certificate.persistence.model.system.User;
import com.jysz.certificate.service.system.UserService;
import com.jysz.webcore.ssh.orm.hibernate.ThreadLocalHolder;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * @author kacarich email:javaengine@outlook.com
 *
 */
public class LogonInterceptor extends AbstractInterceptor {

	
	private static final long serialVersionUID = 1L;

	static final String LOGIN_PAGE_URI = "/loginPage.do";
	
	/**不需要登录就可以访问的URI*/
	static Set<String> noNeedLoginUriSet = new HashSet<String>();
	
	@Resource
	private UserService userService;

	@Override
	public void init() {
		super.init();
		
		noNeedLoginUriSet.add( "/ajaxJsonLogin.do" );
		noNeedLoginUriSet.add( "/login.do" );
		noNeedLoginUriSet.add( "/logout.do" );
		noNeedLoginUriSet.add( "/authCode.do" );
		noNeedLoginUriSet.add( LOGIN_PAGE_URI );
	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		ActionContext actionContext = invocation.getInvocationContext();
		
		HttpServletRequest httpRequest = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
		HttpServletResponse httpResponse = (HttpServletResponse) actionContext.get(StrutsStatics.HTTP_RESPONSE);
		AbstractBaseAction baseAction = (AbstractBaseAction) invocation.getAction();
		User user = baseAction.getUser();
		
		String uri = parseUri( httpRequest );
		
		//采用cas 认证..
//		readCasLogin(httpRequest);
		readCookieAndLogon(httpRequest, httpResponse);
		if(isNeedLogin(uri) && user == null) {
			return forwarePage(httpRequest, baseAction, uri);
		}  else {
			if(user != null) {
				ThreadLocalHolder.set( user.getName());
			}
			return invocation.invoke();
		}
	}

	private String parseUri(HttpServletRequest request) {
		String contextPath = request.getContextPath();
		String uri = request.getRequestURI();
		if(!contextPath.equals("/")) {
			uri = uri.substring(contextPath.length());
		}
		
		
		return uri;
	}
	
	private boolean isNeedLogin(String uri) {
		if(uri == null) {
			return true;
		} 
		return !noNeedLoginUriSet.contains(uri);
	}
	
	private String forwarePage(HttpServletRequest httpRequest, AbstractBaseAction baseAction, String uri) throws IOException, ServletException {
//		 || (uri.indexOf("ajaxJson") == -1)
		if(uri == null) { 
			return AbstractBaseAction.TIME_OUT_PAGE;
		} else if(uri != null && uri.indexOf("ajaxJson") != -1) { //ajaxJson
			baseAction.setJsonText("{timeout: true, flag: false, msg: null, data: null}");
			return AbstractBaseAction.JSON_PAGE;
		} else {
			return AbstractBaseAction.LOGIN_PAGE;
		}
	}
	
	public void readCookieAndLogon(HttpServletRequest request,HttpServletResponse response) throws IOException {
		// 根据cookieName取cookieValue
		Cookie cookies[] = request.getCookies();
		String cookieValue = null;
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				if ("cn.user".equals(cookies[i].getName())) {
					cookieValue = cookies[i].getValue();
					break;
				}
			}
		}
		// 如果cookieValue为空,返回,
		if (cookieValue == null) {
			return;
		}
		String cookieValues[] = cookieValue.split(":");
		long validTimeInCookie = new Long(cookieValues[1]);
		if (cookieValues.length != 3) {

			response.setContentType("text/html;charset=utf-8");

			PrintWriter out = response.getWriter();

			out.println("你正在用非正常方式进入本站...");

			out.close();

			return;

		}

		if (validTimeInCookie < System.currentTimeMillis()) {
			// 删除Cookie
			// clearCookie(response);
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.println("你的Cookie已经失效,请重新登陆");
			out.close();
			return;

		}

		// 取出cookie中的用户名,并到数据库中检查这个用户名,
		String username = cookieValues[0];
		User user = userService.getUserByName(username);
		// 如果user返回不为空,就取出密码,使用用户名+有效时间+密码
		if (user != null) {
			String valueInCookie = cookieValues[2];
			String valueFromUser = user.getName() + ":" + validTimeInCookie
					+ ":" + user.getPassword();
			if (valueFromUser.equals(valueInCookie)) {
				HttpSession session = request.getSession(true);
				session.setAttribute("user", user);
			} else {
				response.setContentType("text/html;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.println("cookie验证错误！");
				out.close();
				return;
			}
		}

	}

	

}
